<template>  
  <div class="app-container">  
    <!-- 搜索表单 -->  
    <el-form ref="searchForm" :model="formData" :inline="true" size="mini">  
      <el-form-item label="销售单号">  
        <el-input v-model="formData.orderNumber" placeholder="请输入销售单号"></el-input>  
      </el-form-item>  
      <el-form-item label="客户编号">  
        <el-input v-model="formData.customerNumber" placeholder="请输入客户编号"></el-input>  
      </el-form-item>  
      <el-form-item label="期望交货日期">  
        <el-date-picker  
          v-model="formData.transactionDate"  
          type="date"  
          placeholder="选择日期"  
          value-format="yyyy-MM-dd">  
        </el-date-picker>  
      </el-form-item>  
      <el-form-item>  
        <el-button type="primary" @click="handleSearch">搜索</el-button>  
        <el-button type="primary" @click="handleAdd">新增</el-button>  
      </el-form-item>  
    </el-form>  

    <!-- 表格 -->  
    <div class="table-container">  
      <el-table  
        :data="tableData"  
        border  
        style="width: 100%"  
        :header-cell-style="{'background-color': '#f5f7fa'}"  
      >  
        <el-table-column type="selection" width="55"></el-table-column>  
        
        <el-table-column label="销售单号" width="150">  
          <template slot-scope="scope">  
            <el-button   
              type="text"  
              @click="handleView(scope.row)">  
              {{scope.row.orderNumber}}  
            </el-button>  
          </template>  
        </el-table-column>  

        <el-table-column prop="customerNumber" label="客户编号" width="120"></el-table-column>  
        <el-table-column prop="transactionDate" label="期望交货日期" width="120"></el-table-column>  
        <el-table-column prop="customerName" label="客户姓名" width="120"></el-table-column>  
        <el-table-column prop="quantity" label="总数量" width="100"></el-table-column>  
        <el-table-column prop="totalAmount" label="总金额" width="120">  
          <template slot-scope="scope">  
            ¥ {{scope.row.totalAmount.toFixed(2)}}  
          </template>  
        </el-table-column>  
        <el-table-column prop="paymentMethod" label="付款方式" width="120"></el-table-column>  
        <el-table-column prop="productType" label="商品类型" width="120"></el-table-column>  
        <el-table-column prop="totalReceivable" label="合计应收金额" width="120">  
          <template slot-scope="scope">  
            ¥ {{scope.row.totalReceivable.toFixed(2)}}  
          </template>  
        </el-table-column>  
        <el-table-column prop="receivedAmount" label="已收金额" width="120">  
          <template slot-scope="scope">  
            ¥ {{scope.row.receivedAmount.toFixed(2)}}  
          </template>  
        </el-table-column>  
        <el-table-column prop="refundStatus" label="回款状态" width="120">  
          <template slot-scope="scope">  
            <el-tag :type="getRefundStatusType(scope.row.refundStatus)">  
              {{scope.row.refundStatus}}  
            </el-tag>  
          </template>  
        </el-table-column>  
        <el-table-column prop="unreceivedAmount" label="未收金额" width="120">  
          <template slot-scope="scope">  
            ¥ {{scope.row.unreceivedAmount.toFixed(2)}}  
          </template>  
        </el-table-column>  
        <el-table-column prop="price" label="单价" width="100">  
          <template slot-scope="scope">  
            ¥ {{scope.row.price.toFixed(2)}}  
          </template>  
        </el-table-column>  
        <el-table-column prop="orderStatus" label="订单状态" width="100"></el-table-column>  
        <el-table-column prop="accountPeriod" label="合计账期" width="100"></el-table-column>  
        <el-table-column prop="createdTime" label="创建时间" width="150"></el-table-column>  
        
        <el-table-column label="操作" width="200" fixed="right">  
          <template slot-scope="scope">  
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>  
            <el-button type="text" @click="handleDelete(scope.row)" style="color: red">删除</el-button>  
            <el-button type="text" @click="handleAttachment(scope.row)">附件</el-button>  
          </template>  
        </el-table-column>  
      </el-table>  
    </div>  

    <!-- 分页 -->  
    <div class="pagination-container">  
      <el-pagination  
        @size-change="handleSizeChange"  
        @current-change="handleCurrentChange"  
        :current-page="formData.pageNum"  
        :page-sizes="[10, 20, 30, 50]"  
        :page-size="formData.pageSize"  
        layout="total, sizes, prev, pager, next, jumper"  
        :total="total">  
      </el-pagination>  
    </div>  

    <!-- 新增/编辑弹窗 -->  
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">  
      <el-form :model="dialogForm" ref="dialogForm" :rules="rules" label-width="100px">  
        <el-row :gutter="20">  
          <el-col :span="12">  
            <el-form-item label="销售单号" prop="orderNumber">  
              <el-input v-model="dialogForm.orderNumber" :disabled="!!dialogForm.id"></el-input>  
            </el-form-item>  
          </el-col>  
          <el-col :span="12">  
            <el-form-item label="客户编号" prop="customerNumber">  
              <el-input v-model="dialogForm.customerNumber"></el-input>  
            </el-form-item>  
          </el-col>  
        </el-row>  

        <el-row :gutter="20">  
          <el-col :span="12">  
            <el-form-item label="客户姓名" prop="customerName">  
              <el-input v-model="dialogForm.customerName"></el-input>  
            </el-form-item>  
          </el-col>  
          <el-col :span="12">  
            <el-form-item label="总数量" prop="quantity">  
              <el-input-number v-model="dialogForm.quantity" :min="0"></el-input-number>  
            </el-form-item>  
          </el-col>  
        </el-row>  

        <el-row :gutter="20">  
          <el-col :span="12">  
            <el-form-item label="总金额" prop="totalAmount">  
              <el-input-number   
                v-model="dialogForm.totalAmount"   
                :min="0"  
                :precision="2">  
              </el-input-number>  
            </el-form-item>  
          </el-col>  
          <el-col :span="12">  
            <el-form-item label="付款方式" prop="paymentMethod">  
              <el-select v-model="dialogForm.paymentMethod" placeholder="请选择">  
                <el-option  
                  v-for="item in paymentMethods"  
                  :key="item"  
                  :label="item"  
                  :value="item">  
                </el-option>  
              </el-select>  
            </el-form-item>  
          </el-col>  
        </el-row>  

        <el-row :gutter="20">  
          <el-col :span="12">  
            <el-form-item label="商品类型" prop="productType">  
              <el-select v-model="dialogForm.productType" placeholder="请选择">  
                <el-option  
                  v-for="item in productTypes"  
                  :key="item"  
                  :label="item"  
                  :value="item">  
                </el-option>  
              </el-select>  
            </el-form-item>  
          </el-col>  
          <el-col :span="12">  
            <el-form-item label="期望交货日期" prop="transactionDate">  
              <el-date-picker  
                v-model="dialogForm.transactionDate"  
                type="date"  
                placeholder="选择日期"  
                value-format="yyyy-MM-dd">  
              </el-date-picker>  
            </el-form-item>  
          </el-col>  
        </el-row>  

        <el-row :gutter="20">  
          <el-col :span="24">  
            <el-form-item label="附件" prop="attachments">  
              <el-upload  
                class="upload-demo"  
                :action="uploadUrl"  
                :on-preview="handlePreview"  
                :on-remove="handleRemove"  
                :before-upload="beforeUpload"  
                :on-success="handleUploadSuccess"  
                :file-list="fileList"  
                multiple>  
                <el-button size="small" type="primary">点击上传</el-button>  
                <div slot="tip" class="el-upload__tip">只能上传jpg/png/pdf文件，且不超过10MB</div>  
              </el-upload>  
            </el-form-item>  
          </el-col>  
        </el-row>  
      </el-form>  
      <div slot="footer" class="dialog-footer">  
        <el-button @click="dialogVisible = false">取 消</el-button>  
        <el-button type="primary" @click="submitDialog">确 定</el-button>  
      </div>  
    </el-dialog>  

    <!-- 查看详情弹窗 -->  
    <el-dialog title="订单详情" :visible.sync="detailVisible" width="60%">  
      <el-descriptions :column="2" border>  
        <el-descriptions-item label="销售单号">{{detailForm.orderNumber}}</el-descriptions-item>  
        <el-descriptions-item label="客户编号">{{detailForm.customerNumber}}</el-descriptions-item>  
        <el-descriptions-item label="客户姓名">{{detailForm.customerName}}</el-descriptions-item>  
        <el-descriptions-item label="总数量">{{detailForm.quantity}}</el-descriptions-item>  
        <el-descriptions-item label="总金额">¥ {{detailForm.totalAmount}}</el-descriptions-item>  
        <el-descriptions-item label="付款方式">{{detailForm.paymentMethod}}</el-descriptions-item>  
        <el-descriptions-item label="商品类型">{{detailForm.productType}}</el-descriptions-item>  
        <el-descriptions-item label="期望交货日期">{{detailForm.transactionDate}}</el-descriptions-item>  
        <el-descriptions-item label="回款状态">{{detailForm.refundStatus}}</el-descriptions-item>  
        <el-descriptions-item label="创建时间">{{detailForm.createdTime}}</el-descriptions-item>  
      </el-descriptions>  
      
      <!-- 附件列表 -->  
      <div class="attachment-list" v-if="detailForm.attachments && detailForm.attachments.length">  
        <div class="title">附件列表</div>  
        <el-table :data="detailForm.attachments" border style="width: 100%">  
          <el-table-column prop="name" label="文件名称"></el-table-column>  
          <el-table-column prop="size" label="文件大小"></el-table-column>  
          <el-table-column label="操作" width="100">  
            <template slot-scope="scope">  
              <el-button type="text" @click="downloadFile(scope.row)">下载</el-button>  
            </template>  
          </el-table-column>  
        </el-table>  
      </div>  
    </el-dialog>  
  </div>  
</template>

<script>  
import { add, list, update, getDetail,delCustomer } from "@/api/monitor/customer";  
import { regionData } from 'element-china-area-data' 

export default {  
  name: 'OrderManagement',  
  
  data() {  
    // 自定义验证规则  
    const validateAmount = (rule, value, callback) => {  
      if (value === '' || value === null) {  
        callback(new Error('请输入金额'))  
      } else if (value <= 0) {  
        callback(new Error('金额必须大于0'))  
      } else {  
        callback()  
      }  
    }  

    return {  
      // 搜索表单数据  
      formData: {  
        orderNumber: '',  
        customerNumber: '',  
        transactionDate: '',  
        pageNum: 1,  
        pageSize: 10  
      },  

      // 表格数据  
      tableData: [  
        {  
          orderNumber: 'XS20240817920',  
          customerNumber: 'SA240816971',  
          transactionDate: '2024-08-17',  
          customerName: '测试客户',  
          quantity: 6,  
          totalAmount: 140.00,  
          paymentMethod: '先款后货',  
          productType: '标准产品',  
          totalReceivable: 140.00,  
          receivedAmount: 0.00,  
          refundStatus: '未回款',  
          unreceivedAmount: 140.00,  
          price: 23.33,  
          orderStatus: '已提交',  
          accountPeriod: 0,  
          createdTime: '2024-08-17',  
          attachments: []  
        }  
      ],  

      // 弹窗表单数据  
      dialogForm: {  
        orderNumber: '',  
        customerNumber: '',  
        customerName: '',  
        quantity: 0,  
        totalAmount: 0,  
        paymentMethod: '',  
        productType: '',  
        transactionDate: '',  
        refundStatus: '',  
        attachments: []  
      },  

      // 详情弹窗数据  
      detailForm: {},  

      // 弹窗控制  
      dialogVisible: false,  
      detailVisible: false,  
      dialogTitle: '',  

      // 上传相关  
      uploadUrl: '/api/upload',  
      fileList: [],  
      
      // 选项数据  
      paymentMethods: ['先款后货', '货到付款'],  
      productTypes: ['标准产品', '定制产品'],  
      refundStatuses: ['未回款', '部分回款', '已回款'],  

      // 分页数据  
      total: 0,  

      // 表单验证规则  
      rules: {  
        orderNumber: [  
          { required: true, message: '请输入销售单号', trigger: 'blur' },  
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }  
        ],  
        customerNumber: [  
          { required: true, message: '请输入客户编号', trigger: 'blur' }  
        ],  
        customerName: [  
          { required: true, message: '请输入客户名称', trigger: 'blur' }  
        ],  
        quantity: [  
          { required: true, message: '请输入数量', trigger: 'blur' },  
          { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }  
        ],  
        totalAmount: [  
          { required: true, message: '请输入总金额', trigger: 'blur' },  
          { validator: validateAmount, trigger: 'blur' }  
        ],  
        paymentMethod: [  
          { required: true, message: '请选择付款方式', trigger: 'change' }  
        ],  
        productType: [  
          { required: true, message: '请选择商品类型', trigger: 'change' }  
        ],  
        transactionDate: [  
          { required: true, message: '请选择期望交货日期', trigger: 'change' }  
        ]  
      }  
    }  
  },  

  created() {  
    this.getList()  
  },  

  methods: {  
    // 获取列表数据  
    async getList() {  
      try {  
        // 这里应该调用实际的API  
        // const { data } = await getOrderList(this.formData)  
        // this.tableData = data.list  
        // this.total = data.total  
        console.log('获取列表数据')  
      } catch (error) {  
        console.error('获取列表数据失败:', error)  
        this.$message.error('获取列表数据失败')  
      }  
    },  

    // 搜索  
    handleSearch() {  
      this.formData.pageNum = 1  
      this.getList()  
    },  

    // 重置搜索  
    resetSearch() {  
      this.$refs.searchForm.resetFields()  
      this.formData.pageNum = 1  
      this.getList()  
    },  

    // 新增  
    handleAdd() {  
      this.dialogTitle = '新增订单'  
      this.dialogVisible = true  
      this.dialogForm = {  
        orderNumber: '',  
        customerNumber: '',  
        customerName: '',  
        quantity: 0,  
        totalAmount: 0,  
        paymentMethod: '',  
        productType: '',  
        transactionDate: '',  
        refundStatus: '',  
        attachments: []  
      }  
      this.fileList = []  
      this.$nextTick(() => {  
        this.$refs.dialogForm && this.$refs.dialogForm.clearValidate()  
      })  
    },  

    // 编辑  
    handleEdit(row) {  
      this.dialogTitle = '编辑订单'  
      this.dialogVisible = true  
      this.dialogForm = { ...row }  
      this.fileList = row.attachments || []  
      this.$nextTick(() => {  
        this.$refs.dialogForm && this.$refs.dialogForm.clearValidate()  
      })  
    },  

    // 查看详情  
    handleView(row) {  
      this.detailVisible = true  
      this.detailForm = { ...row }  
    },  

    // 删除  
    handleDelete(row) {  
      this.$confirm('确认删除该订单吗？', '提示', {  
        confirmButtonText: '确定',  
        cancelButtonText: '取消',  
        type: 'warning'  
      }).then(async () => {  
        try {  
          // await deleteOrder(row.id)  
          this.$message.success('删除成功')  
          this.getList()  
        } catch (error) {  
          console.error('删除失败:', error)  
          this.$message.error('删除失败')  
        }  
      }).catch(() => {})  
    },  

    // 文件上传相关方法  
    handlePreview(file) {  
      // 实现文件预览逻辑  
      console.log('预览文件:', file)  
    },  

    handleRemove(file, fileList) {  
      this.fileList = fileList  
    },  

    beforeUpload(file) {  
      const isValidFormat = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)  
      const isLt10M = file.size / 1024 / 1024 < 10  

      if (!isValidFormat) {  
        this.$message.error('只能上传JPG/PNG/PDF格式的文件!')  
        return false  
      }  
      if (!isLt10M) {  
        this.$message.error('文件大小不能超过10MB!')  
        return false  
      }  
      return true  
    },  

    handleUploadSuccess(response, file, fileList) {  
      this.fileList = fileList  
      this.$message.success('上传成功')  
    },  

    // 提交表单  
    submitDialog() {  
      this.$refs.dialogForm.validate(async (valid) => {  
        if (valid) {  
          try {  
            const data = {  
              ...this.dialogForm,  
              attachments: this.fileList.map(file => ({  
                name: file.name,  
                url: file.url,  
                size: file.size  
              }))  
            }  
            // if (this.dialogForm.id) {  
            //   await updateOrder(data)  
            // } else {  
            //   await createOrder(data)  
            // }  
            this.$message.success('保存成功')  
            this.dialogVisible = false  
            this.getList()  
          } catch (error) {  
            console.error('保存失败:', error)  
            this.$message.error('保存失败')  
          }  
        }  
      })  
    },  

    // 附件处理  
    handleAttachment(row) {  
      this.detailVisible = true  
      this.detailForm = { ...row }  
    },  

    // 下载文件  
    downloadFile(file) {  
      // 实现文件下载逻辑  
      window.open(file.url)  
    },  

    // 分页方法  
    handleSizeChange(val) {  
      this.formData.pageSize = val  
      this.getList()  
    },  

    handleCurrentChange(val) {  
      this.formData.pageNum = val  
      this.getList()  
    },  

    // 工具方法  
    getRefundStatusType(status) {  
      const statusMap = {  
        '未回款': 'warning',  
        '部分回款': 'primary',  
        '已回款': 'success'  
      }  
      return statusMap[status] || 'info'  
    },  

    formatDate(date) {  
      if (!date) return ''  
      const d = new Date(date)  
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`  
    },  

    formatMoney(amount) {  
      return amount ? `¥ ${Number(amount).toFixed(2)}` : '¥ 0.00'  
    }  
  }  
}  
</script>  

<style scoped>  
.app-container {  
  padding: 20px;  
}  

.table-container {  
  margin-top: 20px;  
}  

.pagination-container {  
  margin-top: 20px;  
  text-align: right;  
}  

.form-section {  
  margin-bottom: 20px;  
  padding: 20px;  
  border: 1px solid #EBEEF5;  
  border-radius: 4px;  
}  

.section-title {  
  font-size: 16px;  
  font-weight: bold;  
  margin-bottom: 20px;  
  color: #303133;  
}  

.upload-demo {  
  margin-top: 10px;  
}  

.attachment-list {  
  margin-top: 20px;  
}  

.attachment-list .title {  
  font-size: 14px;  
  font-weight: bold;  
  margin-bottom: 10px;  
}  

.dialog-footer {  
  text-align: right;  
  margin-top: 20px;  
}  

.el-form-item {  
  margin-bottom: 20px;  
}  

.el-table .warning-row {  
  background: oldlace;  
}  

.el-table .success-row {  
  background: #f0f9eb;  
}  

/* 搜索区域样式 */  
.search-form {  
  background: #fff;  
  padding: 20px;  
  margin-bottom: 20px;  
  border-radius: 4px;  
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);  
}  

/* 操作按钮样式 */  
.operate-buttons {  
  margin-bottom: 20px;  
}  

.operate-buttons .el-button {  
  margin-right: 10px;  
}  

/* 表格内链接样式 */  
.link-text {  
  color: #409EFF;  
  cursor: pointer;  
}  

.link-text:hover {  
  text-decoration: underline;  
}  

/* 文件上传样式优化 */  
.el-upload-list {  
  margin-top: 10px;  
}  

.el-upload-list__item {  
  transition: all .3s;  
}  

.el-upload-list__item:hover {  
  background-color: #f5f7fa;  
}  

/* 详情弹窗样式 */  
.el-descriptions {  
  margin: 20px 0;  
}  

.el-descriptions-item__label {  
  width: 120px;  
  color: #606266;  
}  

.el-descriptions-item__content {  
  color: #303133;  
}  
</style>